import { expect } from '@jest/globals';
import fs from 'fs-extra';
import path from 'path';

import { initExecuteCommand, runHvigorAsync } from '../../common/common';
import {
  AbilityType,
  APIType,
  APIVersion,
  CaseLevel,
  LanguageType,
  ModuleTemplateType,
  RuntimeOSType,
  SDKType,
} from '../../plugins/project-builder/models/constants';
import { TestCaseBuilder } from '../../plugins/task-builder/task-case-builder';
import { ProjectBuildOption, TestCaseFun } from '../../plugins/task-builder/test-case';
import { TestTaskOptionBuilder } from '../../plugins/task-builder/test-task-option';

const projectBuilderOption: ProjectBuildOption = {
  template: {
    sdk: SDKType.Single,
    runtimeOS: RuntimeOSType.HarmonyOS,
    apiVersion: APIVersion.API10,
    apiType: APIType.FA,
    language: LanguageType.ArkTs,
    abilityType: AbilityType.Application,
    entryTemplateType: ModuleTemplateType.EmptyAbility
  },
  modulesOption: {
    [ModuleTemplateType.EmptyAbility]: 1,
  }
};

const testFun: (module?: string) => TestCaseFun = (module?: string) => async (project, taskConfig, record) => {
  const projectRoot = project.projectRootPath();
  const commands = initExecuteCommand({
    mode: 'module',
    product: 'default',
    tasks: 'assembleHap'
    , ...(module ? { module: `${module}@default` } : {})
  });
  const result = await runHvigorAsync(projectRoot, commands);
  const isBuildDir = (await fs.readdir(path.resolve(project.getModule('entry').moduleRootPath()))).includes('build');
  record.addStep('执行hap编译构建', result);
  expect(isBuildDir).toBe(true);
  expect(result.stdout).toContain('BUILD SUCCESSFUL');

  const cleanCommands = initExecuteCommand({
    mode: 'module',
    product: 'default',
    tasks: 'clean'
    , ...(module ? { module: `${module}@default` } : {})
  });
  const cleanResult = await runHvigorAsync(projectRoot, cleanCommands);
  record.addStep('执行清除编译构建', cleanResult);
  const isDelBuildDir = (await fs.readdir(path.resolve(project.getModule('entry').moduleRootPath()))).includes('build');
  expect(isDelBuildDir).toBe(false);
  expect(cleanResult.stdout).toContain('BUILD SUCCESSFUL');
};

TestCaseBuilder.builder()
  .caseName('OPEN_LAB_ZOS_MENU_BUILD_FA_API10_ArkTs_002')
  .description('FA模型菜单栏Clean Project')
  .projectBuilderOption(projectBuilderOption)
  .taskConfig(TestTaskOptionBuilder.builder().caseLevel(CaseLevel.L1).build())
  .testFun(testFun('entry'))
  .load();
